package com.lyb.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.lyb.spzx.model.vo.h5.UserInfoVo;
import com.lyb.spzx.user.constant.Constants;
import com.lyb.spzx.user.mapper.UserInfoMapper;
import com.lyb.spzx.user.service.UserInfoService;
import com.lyb.spzx.common.exception.DefinedException;
import com.lyb.spzx.model.dto.h5.UserLoginDto;
import com.lyb.spzx.model.dto.h5.UserRegisterDto;
import com.lyb.spzx.model.dto.system.system.user.UserInfo;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

        //校验参数
        if(!StringUtils.hasText(username) ||
                !StringUtils.hasText(password) ||
                !StringUtils.hasText(nickName) ||
                !StringUtils.hasText(code)) {
            throw new DefinedException(ResultCodeEnum.DATA_ERROR);
        }

        //校验验证码
        String codeValueRedis = redisTemplate.opsForValue().get(Constants.PHONE_CODE + username);
        if (!code.equals(codeValueRedis)){
            throw new DefinedException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //判断用户名即手机号是否被占用
        UserInfo userInfo = userInfoMapper.getByUserName(username);
        if (null != userInfo){
            throw new DefinedException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //保存用户信息
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setNickName(nickName);
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);
        //删除Redis中的code数据
        redisTemplate.delete(Constants.PHONE_CODE + username);
    }

    @Override
    public String login(UserLoginDto userLoginDto, String ip) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        //校验数据
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)){
            throw  new DefinedException(ResultCodeEnum.LOGIN_AUTH);
        }
        //根据username查询
        UserInfo userInfo = userInfoMapper.getByUserName(username);
        if (userInfo == null){
            throw new DefinedException(ResultCodeEnum.LOGIN_ERROR);
        }
        String pwdMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!pwdMd5.equals(userInfo.getPassword())){
            throw new DefinedException(ResultCodeEnum.LOGIN_ERROR);
        }

        //查询状态 0-禁用
        if (userInfo.getStatus() == 0){
            throw new DefinedException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //更新登录信息
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());
        userInfoMapper.updateById(userInfo);

        //生成token
        String token = UUID.randomUUID().toString().replace("-","");
        //保存到Redis
        redisTemplate.opsForValue().set(Constants.USER_LOGIN + token, JSON.toJSONString(userInfo), 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        String userInfoJson = redisTemplate.opsForValue().get(Constants.USER_LOGIN + token);
        if (!StringUtils.hasText(userInfoJson)){
            throw new DefinedException(ResultCodeEnum.LOGIN_AUTH);
        }

        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        UserInfoVo userInfoVo = new UserInfoVo();
        //工具类 将一个对象复制给另一个对象
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }
}
